package com.xiaofeng.pochi.utils;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

@Component
@Configuration
@PropertySource("classpath:wxpay.properties") //读取配置文件
@ConfigurationProperties(prefix = "wxpay") //读取wxpay节点
@Data //使用set方法将wxpay节点中的值填充到当前类的属性中
public class WxPayConfig {

    // 商户号
    private String mchId;

    // 商户API证书序列号
    private String mchSerialNo;

    // 商户私钥文件
    private String privateKeyPath;

    // APIv3密钥
    private String apiV3Key;

    // APPID
    private String appid;

    // 微信服务器地址
    private String domain;

    // 接收结果通知地址
    private String notifyDomain;

    /**
     * 获取商户的私钥文件
     *
     * @param fileName
     * @return {@link PrivateKey }
     * @author: 清梦
     * @dateTime: 2022/5/20 11:27
     */
    public PrivateKey getPrivateKey(String fileName) {
        String s = "-----BEGIN PRIVATE KEY-----\n" +
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQD0RMEI4OjJGNbn\n" +
                "mSOWgafcmiCa2Vompto9Hqerj2DTxrXZSHu8FrNZTIrdU8DP2Pk0r2un/7L+c9J8\n" +
                "b9kb+YVRLZN99AxaZG7hkeDq4xYPWQm04h0m+POMEFoVsgTAyPGw5A+ow/IU+CPJ\n" +
                "4qV85YrjVswNYCUM/gyU0VwMja3+ykQ3NiEHuxdxZmjZvr0RvHZcaMkPr9ijxotL\n" +
                "JptB4GyCOub2ou4Z+uI+pCaSn5GZP4/1bTQsT5xAvPuGAgLfNSdJ/ppGjNQXDqjE\n" +
                "VacscCt2nRnkyRrZGj4/HQvUXznAcFgRWDtJ+oY1GUOAZyfj4oKUGZzceVlu0tnb\n" +
                "ZzMBKtm1AgMBAAECggEBANubFJEO4zoogs0k+MHPP0MtrjKJRmuJhpt8e/HZrYu4\n" +
                "ErWOXO/02Lln/1CMg8RZpXKgY4FeeWYaaxpE1EQ6SIl7GCccyh5aPPW/WR7Tmnmh\n" +
                "6wAcaWkoWI2MBfGLYoqQHfqSjyGDSJlhnYtboLxxAjTxS/KahbTwkg8ZSlBe8Bcn\n" +
                "sBNkAVY54R1RQm3sewHz1uWpsikA+9AeaE8J4h+mH0/n1e8l+lI8G9UMnx1RpoiI\n" +
                "EcGkAtjS5rcB1mWZbmV6y6SEG38FlUIl40gtrwJuWbmHBLTFPwlRnfc/QizeGH/C\n" +
                "n+bp3+KKT9H6zIZ342sxmzASmuAQV7zPx/DDTngbbeECgYEA/GK7JCJ7tEIogT1P\n" +
                "HXeySqtpC40xSfxPUXNi4udAkjAGWjOWo35T/fZtkWLZWHAR8aRt5RvOuqktcKF7\n" +
                "nxnOElAc2OiSfzDiV4oBYrNxpIWXdOv2l2pL7PGHAaXGEfM9Q5Am50XsP+oX0+Ru\n" +
                "CsAmmTM82ovwxLniYWzB+duFqtMCgYEA98RD1u3RsN/XimQYr+kWMY8kIjrF3J0h\n" +
                "9dSgb0iwDhX4vS+DiwzeaQWLIiA71LuN7Pf0VxuIJdm0ZfsnYEPirher4Pvz6tnA\n" +
                "H6uAETzEtHEJRFw5fN6fbknPNk7aeqQ9Z60ezo6PkVqQ9l1IkI+RwYmKOnb/bDmU\n" +
                "7epNxd8ThFcCgYBAbI9qrOa4375pJxY/5mL7jn+09CilwyMYHoUaeH9SEbI9ajfE\n" +
                "qiWUiUf0ua/TVGAwN5HZztxZZ3/y5TWiKjshD5QdhliG4RqVz+OEp1uV7If5z5XV\n" +
                "lsukww58TC2gPV/hFDXqCT5CHmZQr1mrotr3dk3NV7Vw8iYoSlPFjNS1AwKBgD9R\n" +
                "HLUUWX4F9iMbqWNrAYzws587vcy/KyqTh9xoivVOkB5owgkK5NuZ2xCBhEi9FWv1\n" +
                "ga+xDX3+wKc/I7TqJEexLO9188OUmhB912CQUwR5zpB1sQtEKSIaIqYSSKsGxdp0\n" +
                "12aZ7/6JUnpjJGQtDGaVK4n9VxDlNjYGppFmjKpJAoGBAPMs577a0AcOYqzS+x+L\n" +
                "5kKwRuozE/JVO/STcBJG4SydhiIcrj78NcackZxqLkVmAmE1uhKEfFS6dK8Y7xgQ\n" +
                "85fPefwb2zqKruLpApxL6f1AGmYwZrpCUWEFXTmvUZvJU966RCN0dGDeyuys7sXD\n" +
                "pD3xYClJPZJJt38yWhKogrPj\n" +
                "-----END PRIVATE KEY-----";
        return PemUtil.loadPrivateKey(
                s);
    }

    /**
     * 获取签名验证器
     * @author: 清梦
     * @return {@link com.wechat.pay.contrib.apache.httpclient.auth.Verifier }
     * @dateTime: 2022/5/20 11:56
     */
//    @Bean
    public Verifier getVerifier(){
        PrivateKey privateKey = getPrivateKey(privateKeyPath);

        // 获取证书管理器实例
        CertificatesManager instance = CertificatesManager.getInstance();
        // 向证书管理器增加需要自动更新平台证书的商户信息
        try {
            instance.putMerchant(mchId, new WechatPay2Credentials(mchId,
                    new PrivateKeySigner(mchSerialNo, privateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
        } catch (IOException | GeneralSecurityException | HttpCodeException e) {
            e.printStackTrace();
        }
        // ... 若有多个商户号，可继续调用putMerchant添加商户信息
        Verifier verifier = null;
        try {
            verifier = instance.getVerifier(mchId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        // 从证书管理器中获取verifier
        return verifier;
    }

    /**
     * 获取http请求对象
     * @author: 清梦
     * @param verifier
     * @return {@link CloseableHttpClient }
     * @dateTime: 2022/5/20 11:57
     */
//    @Bean
    public CloseableHttpClient getWxPayClient(Verifier verifier){
        PrivateKey privateKey = getPrivateKey(privateKeyPath);
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, privateKey)
                .withValidator(new WechatPay2Validator(verifier));
// ... 接下来，你仍然可以通过builder设置各种参数，来配置你的HttpClient

// 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
        return builder.build();
    }
}
